package com.himiotech.core.framework.config.datasource;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.himiotech.core.framework.config.HimioConfig;
import com.himiotech.core.framework.helper.constant.SysConfigConstatnts;
import com.himiotech.core.project.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

/**
 * 自动化执行初始化 DDL SQL脚本
 * 前提是需要新建好 himio_admin 数据库（utf8mb4）
 *
 * @author wuwenbin
 */
@Slf4j
@Configuration
public class HimioDataSourceInitializer {

    @Autowired
    private HimioConfig himioConfig;
    @Autowired
    @Qualifier("configServiceImpl")
    private IConfigService configService;
    @Value("classpath:/init/himio_admin.sql")
    private Resource sqlScriptHimio;
    @Value("classpath:/init/quartz.sql")
    private Resource sqlScriptQuartz;


    /**
     * 自定义Bean实现业务的特殊需求
     *
     * @param dataSource 数据源配置
     * @return
     */
    @Bean("dataSourceInitializer")
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        //配置文件是否配置了 true
        boolean configInit = himioConfig.isStartInitSql();
        //数据库中是否配置了true
        String himioAdmin;
        boolean quartz = false;
        try {
            himioAdmin = configService.selectConfigByKey(SysConfigConstatnts.START_INIT_SQL);
        } catch (Exception e) {
            himioAdmin = "true";
            quartz = true;
        }
        boolean dbInit = StrUtil.isEmpty(himioAdmin) || Convert.toBool(himioAdmin, false);
        // 设置数据源
        initializer.setDataSource(dataSource);
        //如果是第一次启动程序，那么就看配置文件中是否有配置start-init-sql即可
        log.info("是否执行初始化 sql 脚本，判断因子 ==> configInit :{}，dbInit：{}，判断结果：{}", configInit, dbInit, configInit && dbInit);
        if (configInit && dbInit) {
            log.info("执行初始化 sql 脚本：classpath:/init/{}", sqlScriptHimio.getFilename());
            log.info("执行初始化 sql 脚本：classpath:/init/{}", sqlScriptQuartz.getFilename());
            initializer.setDatabasePopulator(databasePopulator(quartz));
        } else {
            log.info("不执行初始化 sql 脚本");
        }
        return initializer;
    }

    private DatabasePopulator databasePopulator(boolean quartz) {
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        if (quartz) {
            populator.addScripts(sqlScriptHimio, sqlScriptQuartz);
        } else {
            populator.addScripts(sqlScriptHimio);
        }
        //sql脚本中的sql分隔符
        populator.setSeparator(";");
        return populator;
    }
}
